#include "HttpServer.h"

HttpServer::HttpServer()
{
    //server = new QTcpServer(this);
    //connect(server, &QTcpServer::newConnection, this, &HttpServer::handleNewConnection);

    connect(this, &HttpServer::newDescriptor,
            this, &HttpServer::handleDescriptor);

    if (!this->listen(QHostAddress::Any, 8080))
    {
       qFatal("打开服务器失败: %s", this->errorString().toUtf8().constData());
    }
    else
    {
        qDebug("已监听 8080");
    }

}

void HttpServer::handleDescriptor(qintptr socketDescriptor)
{
    // QTcpSocket *socket = server->nextPendingConnection();

    HttpRequestTask *task = new HttpRequestTask(socketDescriptor);
    QThreadPool::globalInstance()->start(task);

    // //class HttpRequestTask : public QRunnable
    // HttpRequestTask *thread = new HttpRequestTask(socket);

    // QThreadPool::globalInstance()->start(thread);
}

void HttpServer::incomingConnection(qintptr socketDescriptor)
{
    emit newDescriptor(socketDescriptor);
}
